import { reactive } from 'vue';
import { defineStore } from 'pinia';
import { SetupStoreId } from '@/enum';

export const useUserStore = defineStore(SetupStoreId.User, () => {
  const userInfo = reactive({
    username: "",
    sex: "",
    age: 18,
  })

  function setUserInfo(username: string, sex: string, age: number) {
    userInfo.username = username;
    userInfo.age = age;
    userInfo.sex = sex;
    // 保存到 localStorage
    localStorage.setItem('userInfo', JSON.stringify(userInfo));
  }

  function resetUserInfo() {
    userInfo.username = "";
    userInfo.age = 18;
    userInfo.sex = "";
    // 清除 localStorage
    localStorage.removeItem('userInfo');
  }

  function loginOut() {
    resetUserInfo()
  }

  function init() {
    const savedUserInfo = localStorage.getItem('userInfo');
    if (savedUserInfo) {
      const parsedUserInfo = JSON.parse(savedUserInfo);
      userInfo.username = parsedUserInfo.username;
      userInfo.age = parsedUserInfo.age;
      userInfo.sex = parsedUserInfo.sex;
    }
  }

  // 初始化时执行
  init()

  return {
    userInfo,
    setUserInfo,
    resetUserInfo,
    loginOut
  };
});
